
import React from 'react';
import PropTypes from 'prop-types';
import {formatMessage} from './intl';
import {Table, Card} from 'antd';
import {Link} from 'react-router-dom';
import {hasPermissions} from './utils';
import {baseDataStatus} from '../Enum';
import {tableSearch, querySearch} from './actions';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import routes from './routes';
import {TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, FIXED_COLUMN_WIDTH} from '../constants';
import {conventEnumValueToString} from '../utils';
import {PERMISSIONS} from './constants';
import {abandonSubDealer} from './api';

class TablePanel extends React.PureComponent {
    state = {
        loading: false
    };
    onChange = (pagination, filters, sorter) => {
        this.props.onChange({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        abandonSubDealer(id, {rowVersion: record.rowVersion}).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.props.refreshListData();
        });
    }
    render() {
        const {pageIndex, pageSize, total, sortedColumnKey, sortedOrder} = this.props;
        const paginationInfo = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.dealerCode',
                defaultMessage: '总代编号'
            }),
            dataIndex: 'dealerCode',
            sorter: true,
            sortOrder: sortedColumnKey === 'dealerCode' && sortedOrder
        }, {
            title: formatMessage({
                id: 'tablePanel.column.dealerName',
                defaultMessage: '总代名称'
            }),
            dataIndex: 'dealerName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '经销商编号'
            }),
            dataIndex: 'code',
            sorter: true,
            sortOrder: sortedColumnKey === 'code' && sortedOrder,
            render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
        }, {
            title: formatMessage({
                id: 'tablePanel.column.name',
                defaultMessage: '经销商名称'
            }),
            dataIndex: 'name',
            sorter: true,
            sortOrder: sortedColumnKey === 'name' && sortedOrder
        }, {
            title: formatMessage({
                id: 'tablePanel.column.shortCode',
                defaultMessage: '简码'
            }),
            dataIndex: 'shortCode',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.shortName',
                defaultMessage: '简称'
            }),
            dataIndex: 'shortName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.countryName',
                defaultMessage: '国家'
            }),
            dataIndex: 'countryName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.provinceName',
                defaultMessage: '省份'
            }),
            dataIndex: 'provinceName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.cityName',
                defaultMessage: '城市'
            }),
            dataIndex: 'cityName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.contactName',
                defaultMessage: '联系人姓名'
            }),
            dataIndex: 'contactName'
        }, {
            title: formatMessage({
                id: 'tablePanel.column.contactPhone',
                defaultMessage: '联系人电话'
            }),
            dataIndex: 'contactPhone',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.address',
                defaultMessage: '地址'
            }),
            dataIndex: 'address',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(baseDataStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.action',
                defaultMessage: '操作'
            }),
            dataIndex: 'action',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    {
                        id: PERMISSIONS.update,
                        children: (
                            <Link key="update" to={routes.update.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.update',
                                    defaultMessage: '编辑'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSIONS.update) && hasPermissions(r.options, PERMISSIONS.update))
                    },
                    {
                        id: PERMISSIONS.abandon,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="abandon"
                                placement="topLeft"
                                onConfirm={this.onClickAbandonBtn}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={formatMessage({
                                    id: 'tablePanel.validate.abandon',
                                    defaultMessage: '是否确认作废？'
                                })}>
                                <a>{
                                    formatMessage({
                                        id: 'tablePanel.operation.abandon',
                                        defaultMessage: '作废'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSIONS.abandon) && hasPermissions(r.options, PERMISSIONS.abandon))
                    }
                ];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <Card>
                <Table
                    className={'white-space-nowrap'}
                    columns={columns}
                    dataSource={this.props.data}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChange}
                    pagination={paginationInfo}
                    rowKey="id"
                    locale={locale}
                    {...TABLE} />
            </Card>
        );
    }
}

TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    refreshListData: PropTypes.func.isRequired,
    total: PropTypes.number.isRequired,
    onChange: PropTypes.func.isRequired,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);

const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    querySearch: () => dispatch(querySearch()),
    onChange: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch())
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(TablePanel);
